/*
 * Copyright © 2008-2014 Stéphane Raimbault <stephane.raimbault@gmail.com>
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */
#include "modbus_task.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "bsp_usart.h"
#include "stdlib.h"

modbus_slave_t* modbus_slave_creat(void* rtu_ctx, uint8_t slave_addr){
		modbus_slave_t* me = MODBUS_MALLOC(sizeof(modbus_slave_t));
		if(me==NULL){
			return NULL;
		}
		me->rtu_slave_ctx = modbus_new_rtu(rtu_ctx, "COM", 115200, 'N', 8, 1); //串口参数不用
		me->slave_mapping =  modbus_mapping_new(16, 16, 25, 16);
		me->slave_mapping->tab_registers[0] = 0;
    me->slave_mapping->tab_registers[1] = 0;
    me->slave_mapping->tab_registers[2] = 0;
    me->slave_mapping->tab_registers[3] = 0;
    me->slave_mapping->tab_registers[4] = 0;
    me->slave_mapping->tab_registers[5] = 0;
    me->slave_mapping->tab_registers[6] = 0;
    me->slave_mapping->tab_registers[7] = 0;
    me->slave_mapping->tab_registers[8] = 0;
		me->slave_mapping->tab_registers[9] = 0;
		me->slave_mapping->tab_registers[10] = 0;
    me->slave_mapping->tab_registers[11] = 0;
    me->slave_mapping->tab_registers[12] = 0;
    me->slave_mapping->tab_registers[13] = 0;
    me->slave_mapping->tab_registers[14] = 0;
    me->slave_mapping->tab_registers[15] = 0;
    me->slave_mapping->tab_registers[16] = 0;
    me->slave_mapping->tab_registers[17] = 0;
    me->slave_mapping->tab_registers[18] = 0;
		me->slave_mapping->tab_registers[19] = 0;
		me->slave_mapping->tab_registers[20] = 0;
    me->slave_mapping->tab_registers[21] = 0;
		modbus_set_error_recovery(me->rtu_slave_ctx,
                              MODBUS_ERROR_RECOVERY_LINK |
                              MODBUS_ERROR_RECOVERY_PROTOCOL);
//		modbus_set_debug(me->rtu_slave_ctx, TRUE);
    /*设置从机地址*/
    modbus_set_slave(me->rtu_slave_ctx, slave_addr);
		me->rtu_addr = slave_addr;
		

		return me;
}
/*modbus从机*/
modbus_slave_t* modbus_slave_ctx;
/*modbus rtu发送*/
uint16_t modbus_rtu_send_uart(void *ctx, void *data, uint16_t count){
	if(sizeof(data)>0){
		HAL_UART_Transmit_DMA(&huart1,data,count);
	}
	 return count;
}
/*modbus rtu处理*/
uint16_t modbus_rtu_handle(void *ctx, void *data, uint16_t count){
	modbus_reply(modbus_slave_ctx->rtu_slave_ctx, data, count, modbus_slave_ctx->slave_mapping);
	return count;
}

int modbus_choose_send(uint8_t ch){

		modbus_set_send(modbus_slave_ctx->rtu_slave_ctx, (int (*)(modbus_t *ctx, const uint8_t *req, int req_length)) modbus_rtu_send_uart);
 return ch;
}

void modbus_rtu_init(uint8_t addr){
	
	  /*创建MODBUS线程， rtu参数传入 dev_mb_rtu*/
		modbus_slave_ctx =  modbus_slave_creat(NULL, addr);
		/*设置modbus 发送函数*/
		if(modbus_slave_ctx != NULL){
			modbus_set_send(modbus_slave_ctx->rtu_slave_ctx, (int (*)(modbus_t *ctx, const uint8_t *req, int req_length)) modbus_rtu_send_uart);
		}
		 
}



